import React, { useEffect, useState } from 'react'
import axios from 'axios'
import { useRequest } from 'ahooks'
import { message, Table, Button, Modal, Form, Input } from 'antd';
import { DeleteOutlined, EditOutlined } from '@ant-design/icons'
import _ from 'lodash';
import CategoryModal from '@/components/CategoryModal';
type stringKey = Record<string, string>;
// 发起网络请求，获取所有新闻类型
const getCategoryListRequest = () => {
    return axios.get(`http://localhost:3000/categories`)
};
// 发起网络请求，删除特定id的新闻类型
const deleteCategoryListRequest = (id: number) => {
    return axios.delete(`http://localhost:3000/categories/${id}`)
};
// 发起网络请求，添加新闻类型
const addCategoryListRequest = (item: any) => {
    return axios.post(`http://localhost:3000/categories`, {
        ...item
    })
};
export default function NewsCategory() {
    const [dataSource, setDataSource] = useState<any>([]);
    // 记录当前选择的行数据信息
    const [currentItem, setCurrentItem] = useState<any>(null);
    // 记录删除按钮的Model对话框是否显示
    const [deleteOpen, setDeleteOpen] = useState(false);
    // 记录添加按钮的Model对话框是否显示
    const [addOpen, setAddOpen] = useState(false);
    // 记录弹出框的类型（添加/修改）
    const [modelType, setModelType] = useState<any>('');
    //对表单数据域进行交互
    const [form] = Form.useForm();
    // useRequest - 获取所有新闻类型
    const { run: getCategoryListData, loading: getCategoryLoading } = useRequest(getCategoryListRequest, {
        throttleWait: 300,
        manual: true,
        onSuccess: (result: any, params) => {
            if (result.status === 200) {
                console.log(result.data);
                setDataSource(result.data);
            }
        },
        onError(e, params) {
            message.warning('请求新闻分类数据失败')
        },
    });
    // useRequest - 获取所有新闻类型
    const { run: addCategoryListData, loading: addCategoryLoading } = useRequest(addCategoryListRequest, {
        throttleWait: 300,
        manual: true,
        onSuccess: (result: any, params) => {
            console.log(result.status);
            if (result.status < 300) {
                getCategoryListData();
                setAddOpen(false);
                form.resetFields();
                message.success('新增新闻分类数据成功')
            }
        },
        onError(e, params) {
            message.warning('新增新闻分类数据失败')
        },
    });
    // useRequest - 获取所有新闻类型
    const { run: deleteCategoryListData, loading: deleteCategoryLoading } = useRequest(deleteCategoryListRequest, {
        throttleWait: 300,
        manual: true,
        onSuccess: (result: any, params) => {
            if (result.status === 200) {
                getCategoryListData();
                setDeleteOpen(false);
                message.success('删除新闻分类成功');
            }
        },
        onError(e, params) {
            message.warning('删除新闻分类失败')
        },
    });
    useEffect(() => {
        getCategoryListData();
    }, []);
    const handelOperation = (item: any, type: string) => {
        switch (type) {
            case 'delete':
                setCurrentItem(item);
                setDeleteOpen(true);
                break;
            case 'add':
                setCurrentItem(null);
                setModelType(type);
                setAddOpen(true);
                break;
            case 'modify':
                console.log('修改');
                setCurrentItem(item);
                setModelType(type);
                setAddOpen(true);
                break;
            default:
                break;
        }

    };
    // 删除对话框中的取消按钮，点击回调事件
    const handleCancel = () => {
        setDeleteOpen(false);
    }
    // 添加对话框的确定按钮，点击回调事件
    const handleAddOk = () => {
        console.log('添加新闻');
        form.validateFields()
            .then((values) => {
                const completeItem = _.cloneDeep(values);
                completeItem.title = values.value;
                addCategoryListData(completeItem);
            })
            .catch((info) => {
                console.log('错误信息:', info);
            });
    };
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            render: (id: string) => {
                return <b>{id}</b>
            }

        },
        {
            title: '栏目名称',
            dataIndex: 'value',
            key: 'value',
        },
        {
            title: '操作',
            render: (item: any) => {
                return (<div>
                    <Button type='primary' shape="circle" style={{ 'marginRight': '10px' }}
                        icon={<EditOutlined />} onClick={() => {
                            handelOperation(item, 'modify')
                        }}></Button>
                    <Button danger shape="circle" style={{ 'marginRight': '10px' }}
                        icon={<DeleteOutlined />} onClick={() => {
                            handelOperation(item, 'delete')
                        }}></Button>

                </div>)
            }
        }
    ];
    return (
        <div>
            <Button type='primary' onClick={() => { handelOperation(null, 'add') }}>添加</Button>
            <Table dataSource={dataSource} columns={columns} loading={getCategoryLoading} 
            rowKey={(item) => item.id} sticky scroll={{ y: '63vh' }}/>
            {/* 删除的对话框 */}
            <Modal
                title={`【${(currentItem as any)?.title}】删除`}
                open={deleteOpen}
                onOk={() => { deleteCategoryListData(currentItem.id) }}
                confirmLoading={deleteCategoryLoading}
                onCancel={handleCancel}
                okText='确定'
                cancelText='取消'
            >
                <p>{`是否要删除【${(currentItem as any)?.title}】,该新闻分类信息?`}</p>
            </Modal>
            {/* 添加的对话框 */}
            {/* <Modal
                title={`新增`}
                open={addOpen}
                onOk={() => { handleAddOk() }}
                confirmLoading={addCategoryLoading}
                onCancel={() => { setAddOpen(false); }}
                okText='确定'
                cancelText='取消'
            >
                <Form
                    name="basic"
                    initialValues={{ remember: true }}
                    autoComplete="off"
                    form={form}
                >
                    <Form.Item
                        label="新闻分类"
                        name="value"
                        rules={[{ required: true, message: '请输入新闻分类!' }]}
                    >
                        <Input />
                    </Form.Item>


                </Form>
            </Modal> */}
            <CategoryModal {...{ addOpen, setAddOpen, modelType, currentItem,getCategoryListData }}></CategoryModal>
        </div>
    )
}
